package main

import (
	"crypto/tls"
	"crypto/x509"
	"flag"
	"io/ioutil"
	"time"

	"gitee.com/jason_elva8325/go-utils/nsq"

	"github.com/golang/glog"
	nsqgo "github.com/nsqio/go-nsq"
)

func main() {
	flag.Parse()
	// load cert
	cert, err1 := tls.LoadX509KeyPair("/tmp/client.pem", "/tmp/client-key.pem")
	if err1 != nil {
		glog.Fatal(err1)
	}

	// load root ca
	caData, err2 := ioutil.ReadFile("/tmp/ca.pem")
	if err2 != nil {
		glog.Fatal(err2)
	}

	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caData)

	conf := nsqgo.NewConfig()
	conf.TlsV1 = true
	conf.TlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      pool,
	}

	env := &nsq.PublisherEnv{
		Address: "127.0.0.1:4150",
		Config:  conf,
	}

	pub := nsq.NewPublish()

	err3 := pub.Init(env)
	if err3 != nil {
		glog.Error(err3)
	}

	for {
		pub.Publish(&nsq.Message{
			Topic:   "test",
			Content: []byte("test_msg" + time.Now().String()),
		})
		time.Sleep(time.Second * 2)
		glog.Infoln("loop")
	}
}
